package com.mspbots.sync.tsheets.client;

import com.fasterxml.jackson.databind.JsonNode;
import com.mspbots.sync.tsheets.SheetsProperties;
import lombok.extern.log4j.Log4j2;
import org.springframework.http.MediaType;
import org.springframework.util.MultiValueMap;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;
import reactor.util.retry.Retry;

import java.time.Duration;

import static java.time.temporal.ChronoUnit.SECONDS;

/**
 * com.mspbots.sync.scheduled.tsheets.TSheetsUserGet
 *
 * @author Alex bob(https://github.com/vnobo)
 * @date Created by 2019/7/25
 */
@Log4j2
public class SheetsGetClient {

    protected final WebClient webClient;

    public SheetsGetClient(SheetsProperties tSheetsProperties) {
        this.webClient = WebClient.builder().baseUrl("https://rest.tsheets.com/api/v1")
                .defaultHeader("Authorization", "Bearer " + tSheetsProperties.getToken())
                .build();
    }

    public Mono<JsonNode> getUserRepository(MultiValueMap<String, String> params) {
        log.debug("TSheets get users by is params:{}.", params);
        return this.request("/users", params);

    }

    public Mono<JsonNode> getTimeSheetsRepository(MultiValueMap<String, String> params) {
        log.debug("TSheets get time sheets by is params:{}.", params);
        return this.request("/timesheets", params);

    }

    protected Mono<JsonNode> request(String path, MultiValueMap<String, String> queryParams) {
        return this.webClient.get().uri(uriBuilder -> uriBuilder.path(path).queryParams(queryParams).build())
                .accept(MediaType.APPLICATION_JSON)
                .retrieve()
                .bodyToMono(JsonNode.class)
                .retryWhen(Retry.backoff(10, Duration.of(5, SECONDS)));
    }
}
